export function idaasScriptBringin() {
  let ONE_ID_SDK_URL = 'https://g.alicdn.com/idaas-frontend/idaas-login-sdk/1.1.201/index.js';
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = ONE_ID_SDK_URL;
    script.onload = () => resolve();
    script.onerror = () => reject();
    document.body.appendChild(script);
  });
}

export function idaasInitialize() {
  let BASE_URL = 'https://oneid.siemens.com.cn';
  let IDAAS_APP_ID = 'siemens_ciam30';

  const SDK = new IDaaSLoginSDK({
    baseUrl: BASE_URL,
    idaasAppId: IDAAS_APP_ID,
    async loginSuccess(data) {
      console.log('loginSuccess', data);
    },
    // 切换语言函数
    async changeLanguageCallback(data) {
      alert('切换语言：' + JSON.stringify(data));
      console.log('changeLanguage', data);
    },
  });

  return {
    /**
     * code / Operation.Failure.Not.Allow.Login / 不允许当前⽤户登录，业务端需要清除⽤户的登录信息
     * code / Operation.Failure.Need.Login / 需要业务端重新执⾏登录
     *
     */
    async getUserToken() {
      return new Promise(async (reslove, reject) => {
        const res = await SDK.getUserToken();
        const { data = {}, code } = res;
        const { access_token, id_token } = data || {};
        if (code === 'Operation.Success') {
          // handleOneIDAccessToken().save(access_token);
          reslove({
            token: access_token,
            idToken: id_token,
          });
        } else {
          setLogin({
            loginInfo: JSON.stringify(handleOneIDCodeExchangeToken().get()),
            channel: 'WEB',
            gid: JSON.stringify(userTarget().gid || ''),
            type: 'FAIL',
            token: JSON.stringify(handleOneIDAccessToken().get() || ''),
            userTokenConfig: handleIdaasUserTokenConfig(),
          });

          // 操作失败，直接提示给⽤户
          // locationReplace();
          // localStorage.clear();
          SDK.clearUserToken();
          reject(res);
        }
      });
    },
    async initUserToken(param = {}) {
      SDK.clearUserToken();
      SDK.initUserToken(param);
    },
    async clearUserToken() {
      SDK.clearUserToken();
      // locationReplace();
    },
  };
  //   return {
  //     /**
  //      * code / Operation.Failure.Not.Allow.Login / 不允许当前⽤户登录，业务端需要清除⽤户的登录信息
  //      * code / Operation.Failure.Need.Login / 需要业务端重新执⾏登录
  //      *
  //      */
  //     async getUserToken() {
  //       return new Promise(async (reslove, reject) => {
  //         const res = await SDK.getUserToken();
  //         const { data = {}, code } = res;
  //         const { access_token, id_token } = data || {};
  //         if (code === 'Operation.Success') {
  //           handleOneIDAccessToken().save(access_token);
  //           reslove({
  //             token: access_token,
  //             idToken: id_token,
  //           });
  //         } else {
  //           setLogin({
  //             loginInfo: JSON.stringify(handleOneIDCodeExchangeToken().get()),
  //             channel: 'WEB',
  //             gid: JSON.stringify(userTarget().gid || ''),
  //             type: 'FAIL',
  //             token: JSON.stringify(handleOneIDAccessToken().get() || ''),
  //             userTokenConfig: handleIdaasUserTokenConfig(),
  //           });
  //           // 操作失败，直接提示给⽤户
  //           locationReplace();
  //           localStorage.clear();
  //           SDK.clearUserToken();
  //           reject(res);
  //         }
  //       });
  //     },
  //     async initUserToken(param = {}) {
  //       SDK.clearUserToken();
  //       SDK.initUserToken(param);
  //     },
  //     async clearUserToken() {
  //       SDK.clearUserToken();
  //       locationReplace();
  //     },
  //   };
}
export function locationReplace() {
  window.location.replace(`${BASE_URL}?idaasAppId=${IDAAS_APP_ID}`);
}

export const getQueryString = (qname = 'code') => {
  const urlstr = window.location.href;
  if (urlstr.indexOf('?') !== -1) {
    const str = urlstr.split('?')[1];
    const qreg = new RegExp(`(^|&)${qname}=([^&]*)(&|$)`, 'i');
    const r = str.match(qreg);
    if (r != null) {
      return unescape(r[2]);
    }
    return '';
  }
  return '';
};
